package com.clear.auth.domain.service.impl;


import com.alibaba.fastjson.JSON;
import com.clear.auth.common.enums.IsDeletedFlagEnum;
import com.clear.auth.domain.convert.AuthRolePermissionConverter;
import com.clear.auth.domain.entity.AuthRolePermissionBO;
import com.clear.auth.domain.service.AuthRolePermissionDomainService;
import com.clear.auth.infra.basic.entity.AuthRolePermission;
import com.clear.auth.infra.basic.service.AuthRolePermissionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.LinkedList;
import java.util.List;

@Service
@Slf4j
public class AuthRolePermissionDomainServiceImpl implements AuthRolePermissionDomainService {

    @Resource
    private AuthRolePermissionService authRolePermissionService;

    /**
     * 新增角色权限
     *
     * @param authRolePermissionBO
     * @return
     */
    @Override
    public Boolean add(AuthRolePermissionBO authRolePermissionBO) {
        if (log.isInfoEnabled()) {
            log.info("AuthRolePermissionDomainServiceImpl.add.bo:{}", JSON.toJSONString(authRolePermissionBO));
        }

        // ==============================数据量小的插入方式================================
//        Long roleId = authRolePermissionBO.getRoleId();
//        authRolePermissionBO.getPermissionIdList().forEach(permissionId -> {
//            AuthRolePermission authRolePermission = new AuthRolePermission();
//
//            authRolePermission.setRoleId(roleId);
//            authRolePermission.setPermissionId(permissionId);
//            authRolePermission.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());
//            // 每次都会与数据库交互
//            authRolePermissionService.insert(authRolePermission);
//        });

        // ==============================减少与数据库io的方式================================
        Long roleId = authRolePermissionBO.getRoleId();
        List<AuthRolePermission> authRolePermissionList = new LinkedList<>();
        authRolePermissionBO.getPermissionIdList().forEach(permissionId -> {
            AuthRolePermission authRolePermission = new AuthRolePermission();

            authRolePermission.setRoleId(roleId);
            authRolePermission.setPermissionId(permissionId);
            authRolePermission.setIsDeleted(IsDeletedFlagEnum.UN_DELETED.getCode());

            authRolePermissionList.add(authRolePermission);
        });
        int count = authRolePermissionService.batchInsert(authRolePermissionList);

        return count > 0;
    }
}
